package com.cty.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: cty
 * @Date: 2020/3/12 17:14
 * @Description:  控制器  下载
 * @version: 1.0
 */
@Controller
public class DemoController {
    @RequestMapping("upload")
    public String upload(MultipartFile file, String name, HttpServletRequest req) throws IOException {
        System.out.println("name: "+name);

        // 获取文件名后缀
        System.out.println("file: "+file);  // file: org.springframework.web.multipart.commons.CommonsMultipartFile@2ebd072
        String fileName = file.getOriginalFilename();
        System.out.println("fileName: "+fileName);  // fileName: 5328914_tianyuchenc.png
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        // 判断上传数据类型并上传到指定路径
        if(suffix.equalsIgnoreCase(".png") || suffix.equalsIgnoreCase(".jpg")  || suffix.equalsIgnoreCase(".jpeg")){
            String uuid = UUID.randomUUID().toString();
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(req.getServletContext().getRealPath("upload"),uuid+suffix));
            return "/index.jsp";
        }else {
            return "/typeError.jsp";
        }



    }
}
